package com.guyaogg.gulimall.testssoserver.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author 顾遥
 */
@Slf4j
@Controller
public class LoginController {

    private final StringRedisTemplate redisTemplate;

    public LoginController(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          Model model,
                          HttpServletResponse response) {
        // 登录成功跳转,跳回之前页面
        if (username != null) {
            log.info("成功");
            String s = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(s, username);
            Cookie ssoToken = new Cookie("sso_token", s);
            // 保存 cookie ，保证单点登录
            response.addCookie(ssoToken);
            return "redirect:" + url + "?token="+s;

        } else {
            log.info("失败");
            model.addAttribute("url", url);
            return "login";
        }

    }

    @GetMapping("login.html")
    public String login(@RequestParam("redirect_url") String url, Model model,
                        @CookieValue(value = "sso_token",required = false) String sso_token) {
        if(!ObjectUtils.isEmpty(sso_token)){
            // 说明之前有登录，跳回去
            return "redirect:" + url + "?token="+sso_token;
        }
        model.addAttribute("url", url);
        // 登录成功跳转,跳回之前页面
        return "login";
    }
}
